import { Table } from 'antd';
import { ComponentProps, useLayoutEffect, useRef, useState } from 'react';

import classes from './index.module.scss';

type Props = {
  search?: React.ReactNode;
} & ComponentProps<typeof Table>;

const TableFrame: React.FC<Props> = ({ rowKey = 'id', size = 'small', search, ...props }) => {
  const tableRef = useRef<HTMLDivElement>(null);
  const [headerHeight, setHeaderHeight] = useState(400);

  useLayoutEffect(() => {
    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        if (tableRef.current) {
          const { height } = entry.contentRect;
          const headerRow = tableRef.current.querySelector('.ant-table-thead > tr') as HTMLDivElement;
          setHeaderHeight(height - (headerRow?.offsetHeight || 40) - 64);
        }
      }
    });
    resizeObserver.observe(tableRef.current!);
    return () => resizeObserver.disconnect();
  }, []);

  return (
    <div className={classes.wrap}>
      {search}

      <div className={classes.content}>
        <div className={classes.overflow} ref={tableRef}>
          <Table {...props} rowKey={rowKey} size={size} scroll={{ y: headerHeight, x: '100%' }} />
        </div>
      </div>
    </div>
  );
};

export default TableFrame;
